// pages/uploaddge/uploaddge.js
import {request} from '../../request/index.js'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min");
var qqmapsdk;
import {upload} from '../../utils/qiniuUploader'
const utils = require("../../utils/util");
var util = require('../../utils/jingweiduzhuanhuan')  
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadToken: '', // 七牛云上传存储
    tempFilePaths: '',
    imgList: [], // 上传成功的图片数组
    textValue: '', // 隐患描述
    // 定位地点显示
    posName: '点击进行定位选择',
    // 隐患上报表单信息
    dgeForm:{
      dgeName: '',// 隐患名称 dgeName,
      dgeInfo: '',// 隐患信息
      dgeTypeId: '',// 隐患分类编号 dgeTypeId
      dgeLevel: '',// 隐患等级 dgeLevel
      dgeLng: '',// 隐患经度
      dgeLat: '',// 隐患纬度
      dgeFound: '',//发起人编号
      deptId: '',  // 部门编号 deptId
    },
    // 预览
    fileList: [],
    // 上传图片用的数组
    fenlei: '请选择隐患分类',
    showfenlei: false,
    level: '请选择隐患等级',
    showlevel:false,
    dept:'请选择供电所',
    showdept:false,
    FlForm:[],
    LeForm:[
      {name : "一般" },
      {name : "重要" },
      {name : "严重" }],
    DeForm:[],
   DeIdForm:[]
  },

  // 获取定位权限
 handleGetPos(){
  // let that = this;
  // wx.getLocation({
  //   type: 'gcj02',
  //   success(res) {
  //     var lat = res.latitude
  //     var lng = res.longitude
  //     console.log(lat + "||latitude" );
  //     console.log(lng + "||longitude");
  //     // wgs84转百度坐标系(wgs->gcj->baidu)
  //     // var gcj = util.transformFromWGSToGCJ(lat,lng)
  //     var baidu = util.transformFromGCJToBaidu(lat,lng)
  //     console.log(baidu)
  //     // console.log(gcj);
  //     that.setData({
  //       longitude: baidu.longitude,
  //       latitude: baidu.latitude
  //     }, () => {
  //       // that.jingWeiduToDiZhi(res.latitude,res.longitude);
  //     });
  //   }
  // })
   let that = this
  wx.chooseLocation({
    success:function(res){
      console.log(res)
      // wgs -> gcj
    //  var result = util.transformFromWGSToGCJ(res.latitude,res.longitude)
    //  console.log(result)
    // chooseLocation 是gcj02
    //  gcj02->baidu
     var result2 = util.transformFromGCJToBaidu(res.latitude,res.longitude)
     console.log(result2)
     that.setData({
      posName: res.address,
      "dgeForm[0].dgeLat": result2.latitude,
      "dgeForm[0].dgeLng": result2.longitude
    })
      // console.log(res.address)
     
    }
   })
  },

  // get fenlei
  async chooseFl(){
    const res = await request({
      url: '/type/allType',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
    })
    // console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      var Fllist = res.data.data
      if (Fllist[0]){
        var arr = [];
        Fllist.forEach(function(item){
          arr.push({"name":item.dgeTypeName, "subname": item.dgeTypeInfo,"id":item.dgeTypeId})
        })
        this.setData({
          showfenlei: true,
          FlForm: arr
        })
        // console.log(this.data.FlForm)
      }
    }
  },
  onFlClose(){
    this.setData({
      showfenlei:false
    })
  },
  onFlSelect(event) {
    // console.log(event.detail);
    this.setData({
      "dgeForm[0].dgeTypeId": event.detail.id,
      fenlei:event.detail.name
    })
  },

  // get Level
  chooseLe(){
    this.setData({
      showlevel: true
    })
  },
  onLeClose(){
    this.setData({
      showlevel:false
    })
  },
  onLeSelect(event) {
    console.log(event.detail);
    this.setData({
      "dgeForm[0].dgeLevel": event.detail.name,
     level:event.detail.name
    })
  },

  // get DeptId
async chooseDe(){
  if (wx.getStorageSync('role') === 'admin'){
    const res = await request({
      url: '/dept/allBranch',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
    })
    // console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      var Delist = res.data.data
      if (Delist[0]){
        var arr = [];
        var arr1 = [];
        Delist.forEach(function(item){
          arr.push(item.deptName)
          arr1.push(item.deptId)
        })
        this.setData({
          showdept: true,
          DeForm: arr,
          DeIdForm: arr1
        })
        // console.log(this.data.DeForm)
      }
    }
  }
  else{
    const res1 = await request({
      url: '/dept/showInfo/' + wx.getStorageSync('deptId'),
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
    })
    console.log(res1)
    if (res1.data.status !== 200){
      var title = res1.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      var Delist = res1.data.data
      console.log(Delist)
        var arr = [];
        var arr1 = [];
        arr.push(Delist.deptName)
        arr1.push(Delist.deptId)
      this.setData({
        showdept: true,
        DeForm: arr,
        DeIdForm: arr1
      })
      console.log(this.data.DeForm)
    }
  }
 
},
onDeClose(){
  this.setData({
    showdept :false
  })
  },
  onDeClose1(){
    this.setData({
      showdept :false,
      dept:'请选择供电所(选填)',
      "dgeForm[0].deptId": ''
    })
    },
  onDeSelect(event) {
    // console.log(event.detail);
    var index = event.detail.index
    var arr = this.data.DeIdForm
    var id = arr[index]
    this.setData({
      "dgeForm[0].deptId": id,
       dept:event.detail.value
    })
    // console.log(this.data.dgeForm[0].deptId)
    this.onDeClose()
  },

  // 文件上传完毕回调函数after-read
  afterRead(event) {
    const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    this.setData({
        fileList:[...this.data.fileList, ...file]
    })
    // this.uploadImg(file);
},

// 删除图片
delete(event) {
    // console.log(event)
    let imgDelIndex = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(imgDelIndex,1)
    // console.log('删除图片的',fileList)
    this.setData({
        fileList
    })
    // this.uploadImg(fileList)
},

msInput(event) {
  this.setData({
    textValue: event.detail
  })
  // console.log(textValue)
},
mcInput(event){
  this.setData({
    "dgeForm[0].dgeName": event.detail
  })
},
async uploadImg(){
  // 有图片上传则七牛云 
  if (this.data.fileList[0]){
    wx.showLoading({
      title: '玩命上传中',
    })
    const res = await request({
      url: '/other/upload',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
    })
    console.log(res)
    let _this = this
    if (res.data.status === 200 ) {
      _this.setData({
          uploadToken: res.data.data.uploadToken
      }, () => {
         var filepath = _this.data.fileList
         console.log(filepath)
        for (var i = 0 ; i< filepath.length ; i++){
          var file = filepath[i].url
          console.log(file)
           upload(file, res => {
            console.log(res)
            _this.setData({
              tempFilePaths:'http://ele.qiniu.heilama.com' +"/"+ res.key,
              imgList: _this.data.imgList.concat("http://ele.qiniu.heilama.com" + "/" + res.key)
            },() => {
              console.log(_this.data.tempFilePaths)
              console.log("imgList" + _this.data.imgList),
              console.log(_this.data.imgList.length)
              if (filepath.length === _this.data.imgList.length){
                console.log('七牛云上传完毕')
                var photo = _this.data.imgList
                var strphoto = photo.toString(',')
                var content = _this.data.textValue
                var info = content + 'imgGroup:' + strphoto
                console.log(info)
                console.log(_this.data.fileList)
                _this.setData({
                  "dgeForm[0].dgeInfo": info,
                  "dgeForm[0].dgeFound":wx.getStorageSync('empId')
              },() => {
                wx.hideLoading({
                  success: (res) => {},
                })
                _this.submit()
              })
              }
            })
          }, (error) => {
            console.log('error' + error)
          }, {
          //这里是你所在大区的地址
            uploadURL: 'https://up-z2.qiniup.com',
            // domain: 'qm94gq3eu.hn-bkt.clouddn.com',
            // domain: 'https://ele.qiniu.heilama.com',
            domain: 'ele.qiniu.heilama.com',
      //这里的uptoken是后端返回来的
            uptoken: _this.data.uploadToken,
          })
          }
      })
    }
  }
  else {
    this.setData({
      "dgeForm[0].dgeInfo": this.data.textValue,
      "dgeForm[0].dgeFound":wx.getStorageSync('empId')
    },() => {
      this.submit()
    })
  }
}
  ,
  // submit
  async submit(){
    var subForm = this.data.dgeForm[0]
    console.log(subForm)
    const res = await request({
      url: '/danger/create',
      data: this.data.dgeForm[0],
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "post",
    })
    console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 1500
      })
      setTimeout(function(){
        wx.redirectTo({
          url: '/pages/fail/fail',
        })
      },1500)
    }else {
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 1500
      })
      setTimeout(function(){
        wx.redirectTo({
          url: '/pages/success/success',
        })
      },1500)
    }
  }
,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'TUHBZ-ZPFKU-XQAVA-BC4M4-ER4IZ-BXBLL'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if ( wx.getStorageSync('token')){
      this.checkToken()
    }
    else {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },
  async checkToken(){
    var token = wx.getStorageSync('token')
    if (token){
      const res = await request({
        url: '/user/verify',
        header:{
          'Authorization':'Bearer '+ token,
        },
        method: "get",
      })
      if (res.data.status !== 200){
         var title = res.data.msg ? res.data.msg :null
        if (title){
        wx.showToast({
          title: title,
          icon: 'none',
          duration: 2000
          })
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    } 
  }
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh({
      success: (res) => {},
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})